/*
 * Project it.battlehorse.rcp.ioc
 * Created on Apr 9, 2006
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * A copy of the LGPL is available also at
 * http://www.gnu.org/copyleft/lesser.html
 * 
 */
package it.battlehorse.ioc;


import org.objectweb.asm.MethodAdapter;
import org.objectweb.asm.MethodVisitor;

import static org.objectweb.asm.Opcodes.* ;
import static it.battlehorse.ioc.IOCConstants.*;

/**
 * The constructor writer which effectively modifies class constructors injecting invocations
 * to the Service Locator plug-in. 
 * 
 * @author battlehorse
 * @since Apr 9, 2006
 */
public class ConstructorWriter extends MethodAdapter {
	
	private boolean found;

	public ConstructorWriter(MethodVisitor mv) {
		super(mv);
		found = false;
	}
	
	@Override
	public void visitMethodInsn(int opcode, String owner, String name, String desc) {
		if (opcode == INVOKESPECIAL && !found) {
			super.visitMethodInsn(opcode, owner, name, desc);
			mv.visitVarInsn(ALOAD, 0);
			mv.visitMethodInsn(INVOKESTATIC, 
							   SERVICE_LOCATOR_CLASS, 
							   SERVICE_LOCATOR_METHOD, 
							   SERVICE_LOCATOR_PARAMETERS);			
			found = true;
		}
		else {
			super.visitMethodInsn(opcode, owner, name, desc);
		}
		
	}
		
}
